package com.ziyia.jetpack;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

public class MainActivity extends AppCompatActivity {

    private TextView text = null;
    private MainViewModel mainViewModel = null;
    private SharedPreferences preferences = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Lifecycle lifecycle = getLifecycle();
        lifecycle.addObserver(new MyObserver(lifecycle));


        text = findViewById(R.id.text);

        preferences = getPreferences(MODE_PRIVATE);

        int c = preferences.getInt("count_reserved", 0);

        mainViewModel = new ViewModelProvider(MainActivity.this, new MainViewModelFactory(c)).get(MainViewModel.class);

        mainViewModel.getMutableLiveData().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                text.setText(integer.toString());
            }
        });
        mainViewModel.getUser().observe(this, new Observer<User>() {
            @Override
            public void onChanged(User user) {
                Log.d("fun", "onChanged: ");
                text.setText(user.getName());
            }
        });


        mainViewModel.getRefreshResult().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.d("测试", s);
            }
        });
    }

    public void ijj(View view) {
        mainViewModel.plusOne();
    }



    public void clear(View view) {
        mainViewModel.clear();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Integer value = mainViewModel.getMutableLiveData().getValue();
        preferences.edit().putInt("count_reserved", value == null ? 0 : value);
    }

    public void getUserBtn(View view) {
        String random = String.valueOf(Math.random());
        Log.d("random", random);
        mainViewModel.getUser(random);
    }

    public void test(View view) {
        String random = String.valueOf(Math.random());
        mainViewModel.refresh(random);
    }
}